import React from "react";
import ReactDOM from "react-dom/client";

// 引入样式
import "./index.css";

class App extends React.PureComponent {
  listRef = React.createRef();

  state = {
    counter: 0,
    list: [],
  };

  componentDidMount() {
    // 计时器
    setInterval(() => {
      const newMsg = `Hello ${this.state.list.length + 1}`;

      this.setState({
        list: [...this.state.list, newMsg],
      });
    }, 1000);
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // 加上判断，避免任何数据的变化，都执行如下代码 根据数据来控制
    if (prevState.list.length !== this.state.list.length) {
      console.log(this.listRef.current);
      // this.listRef.current 真实DOM对象
      // this.listRef.current.scrollTop = this.listRef.current.scrollHeight;
      // this.list
      const a = this.listRef.current;
      a.scrollTop = a.scrollHeight;
    }
  }

  render() {
    return (
      <div className="list" ref={this.listRef}>
        {this.state.list.map((item, index) => {
          return (
            <div key={index} className="item">
              {item}
            </div>
          );
        })}
      </div>
    );
  }
}

ReactDOM.createRoot(document.querySelector("#root")).render(<App />);
